<?php

namespace app\admin\controller\user;

use app\admin\model\rush\Order;
use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['inviter'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                //邀请二维码
                $v->invitation_qr = $v->invitation_qr ? request()->domain().$v->invitation_qr : '';
                $v->hidden(['password', 'salt']);
                //银行卡信息
                $v->bank_name = $v->bank_name." ".$v->bank_card_no." ".$v->bank_card_holder;
                //推荐人
                $v->getRelation('inviter')->visible(['nickname','mobile']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Db::startTrans();
        try {
            Auth::instance()->delete($row['id']);
            //抢购商品
            Db::name('rush_goods')->where('seller_id',$row['id'])->whereOr('buyer_id',$row['id'])->delete();
            //抢购订单
            $rush_order_list = Order::where('seller_id',$row['id'])->whereOr('buyer_id',$row['id'])->select();
            foreach($rush_order_list as $v){
                //委托订单
                Db::name('rush_order_entrust')->where('order_id',$v['id'])->delete();
                $v->delete();
            }
            //抢购订单提货地址
            Db::name('rush_order_address')->where('user_id',$row['id'])->delete();
            //商城购物车
            Db::name('cart')->where('user_id',$row['id'])->delete();
            //商城订单
            Db::name('shop_order')->where('user_id',$row['id'])->delete();
            //商城订单商品
            Db::name('shop_order_goods')->where('user_id',$row['id'])->delete();
            //收货地址
            Db::name('user_address')->where('user_id',$row['id'])->delete();
            //优惠券
            Db::name('user_coupon')->where('user_id',$row['id'])->delete();
            //兑换积分
            Db::name('user_score_exchange')->where('user_id',$row['id'])->delete();
            //积分记录
            Db::name('user_score_log')->where('user_id',$row['id'])->delete();
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }

    /**
     * 编辑银行卡信息
     */
    public function editcard($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
